#include "head.h"
#include "signal.h"
int kill(pid_t,int);
void signal_test()
{
	pid_t	pid;
	pid = fork();
	if(pid==0){
		sleep(1);
		kill(getppid(),SIGHUP);

	}
	else if(pid>0){
		while(1);
		
	}
	
}
void sigHandler(int no)
{
	int wstatus;
	pid_t wpid;
	
	if(no == SIGINT){
		printf("parent receive SIGINT\n");
	}
	else {
		while((wpid=waitpid(-1,&wstatus,0))!=-1){
			DEBUG_MSG("child %d die ",wpid);
			if (WIFEXITED(wstatus)) {
				printf("exited, status=%d\n", WEXITSTATUS(wstatus));
			} else if (WIFSIGNALED(wstatus)) {
				printf("killed by signal %d\n", WTERMSIG(wstatus));
			} else if (WIFSTOPPED(wstatus)) {
				printf("stopped by signal %d\n", WSTOPSIG(wstatus));
			} else if (WIFCONTINUED(wstatus)) {
				printf("continued\n");
			}
		}
	}
	
}
void sigHandler2(int no)
{
	int wstatus;
	pid_t wpid;
	
	if(no == SIGINT){
		printf("son receive SIGINT\n");
	}
}
#if 1
// void signal_recycle_child_test()
int main()
{
	sigset_t set,oldSet;
	size_t i;
	sigemptyset(&set);
	sigaddset(&set,SIGCHLD);
	sigprocmask(SIG_BLOCK,&set,&oldSet);
	for ( i = 0; i < 15; i++)
	{
		pid_t p = fork();
		if(p == 0){
			break;
		}
		
	}
	if(i==15){
		
		struct sigaction  act,oldact;
		act.sa_handler = sigHandler;
		sigemptyset(&(act.sa_mask));
		act.sa_flags=0;

		sigaction(SIGCHLD,&act,&oldact);
		sigaction(SIGINT,&act,&oldact);
		sigprocmask(SIG_UNBLOCK,&set,&oldSet);
		int cnt=60;
		while (cnt--)
		{
			sleep(1);
			/* code */
		}
		
	}
	else{
		struct sigaction  act,oldact;
		act.sa_handler = sigHandler2;
		act.sa_flags=0;
		

		// sigaction(SIGCHLD,&act,&oldact);
		if(i==0){
			sigaction(SIGINT,&act,&oldact);
		}
		DEBUG_MSG("child %d :%d\n",i+1,getpid());
		int cnt=30;
		while (cnt--)
		{
			sleep(1);
			/* code */
		}
		return i;
		
	}
	return 0;
}
#endif